package com.solution.pc.home.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.rsa.Base64;
import com.solution.common.utils.sms.MySSLProtocolSocketFactory;

@RequestMapping("/pc/demo")
@Controller
public class DemoController extends BaseController {
	
	/**
	 * 获取accessToken链接
	 */
	private static final String GET_ACCEESS_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET";
	/**
	 * app key
	 */
	private static final String CLIENT_ID = "3nTjCrysbDKdEHTYKCdmmGnn";
	/**
	 * secret key
	 */
	private static final String CLIENT_SECRET = "r9PGd5blLubtXR3aTGhDGrRQLl9Ll0GT ";
	/**
	 * access_token有效期一个月
	 */
	private static final String ACCESS_TOKEN = "24.13a8af83db6a770834629cdb0344fcee.2592000.1529637955.282335-11283782";
	/**
	 * 陈列鉴别接口地址
	 */
	private static final String IMAGE_DETECTION_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/detection/zhaiugo?access_token=ACCESS_TOKEN";
	
	/**
	 * 已获取的accessToken,有效期约为一个月,不要重复运行获取
	{
	    "access_token":"24.13a8af83db6a770834629cdb0344fcee.2592000.1529637955.282335-11283782",
	    "session_key":"9mzdCrdzZYP8MkL0cmxzekXq16M5VbkZVMjSoWsF+u/R2OHdY3Ssy0AgIGv35frCf/R+aBTR3H4jfAUn/dhqRofprplVmg==",
	    "scope":"public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_advanced_general_classify wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base",
	    "refresh_token":"25.ac6fa7fca0359d5351152639218b64ae.315360000.1842405955.282335-11283782",
	    "session_secret":"7b679b688fc17bcfef46812ec4a7daa8",
	    "expires_in":2592000
	}
	**/

	/**
	 * 图片识别接口
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月23日 下午2:31:42
	 */
	@RequestMapping(value="/imageDetection", produces="text/html;charset=UTF-8")
	@ResponseBody
	public String imageDetection(HttpServletRequest request){
		// 返回值
		JSONObject result = new JSONObject();
		// 获取文件
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
		Set<String> keySet = fileMap.keySet();
		Iterator<String> iterator = keySet.iterator();
		byte[] data = null;
		try {
			while (iterator.hasNext()) {
				String key = iterator.next();
				MultipartFile multipartFile = fileMap.get(key);
				// 上传
				InputStream is = multipartFile.getInputStream();
				data = new byte[is.available()];
				is.read(data);
				is.close();
				String base64Str = Base64.encode(data);
				JSONObject detectionResult = JSONObject.parseObject(ImageDetection(base64Str));
				result.put("code", "1");
				result.put("detectionResult", detectionResult);
				result.put("msg", "识别成功");
			}
		} catch (Exception e) {
			result.put("code", "0");
			result.put("msg", "识别失败");
			e.printStackTrace();
		}
		return result.toJSONString();
	}
	
	@RequestMapping("/toImageDetection")
	public String toImageDetection(HttpServletRequest request){
		return "/image_detection";
	}
	
	/**
	 * 获取accessToken,有效期大致为一个月,因此不需要多次运行
	 * https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【百度云应用的AK】&client_secret=【百度云应用的SK】
	 * @param apiId
	 * @param key
	 * @author xkl
	 * @date 2018年5月23日 上午11:14:38
	 */
	public static String getAccessToken(){
		String url = GET_ACCEESS_TOKEN_URL.replace("CLIENT_ID", CLIENT_ID).replace("CLIENT_SECRET", CLIENT_SECRET);
		String respStr = "";
		try {
			respStr = doPost(url, "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respStr;
	}
	
	public static String ImageDetection(String base64Str){
		String url = IMAGE_DETECTION_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
		String respStr = "";
		JSONObject object = new JSONObject();
		object.put("image", base64Str);
		try {
			respStr = doPost(url, object.toJSONString());
//			System.out.println(url);
//			System.out.println(object.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respStr;
	}
	
	public static void main(String[] args) {
		InputStream is = null;
		byte[] data = null;
	    try {
	    	is = new FileInputStream("C:/Users/Administrator/Desktop/杯具/IMG_20180517_155248.jpg");
//	    	BufferedImage image = ImageIO.read(new File("C:/Users/Administrator/Desktop/杯具/IMG_20180518_105821_1.jpg"));
//	        Graphics g = image.getGraphics();
//	        g.setColor(Color.RED);//画笔颜色
//	        g.drawRect(186, 455, 2963, 2417);//矩形框(原点x坐标，原点y坐标，矩形的长，矩形的宽)
//	        //g.dispose();
//	        FileOutputStream out = new FileOutputStream("C:/Users/Administrator/Desktop/杯具/识别/IMG_20180518_105821_1.jpg");//输出图片的地址
//	        ImageIO.write(image, "jpeg", out);data = new byte[is.available()];
	    	data = new byte[is.available()];
	    	is.read(data);
	    	is.close();
			String base64Str = Base64.encode(data);
			JSONObject detectionResult = JSONObject.parseObject(ImageDetection(base64Str));
			System.out.println(detectionResult.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * https post请求
	 * @param url
	 * @param responeJsonStr
	 * @return
	 * @throws IOException
	 * @throws HttpException
	 * @author xkl
	 * @date 2018年5月23日 上午11:13:49
	 */
	public static String doPost(String url, String responeJsonStr) throws IOException, HttpException {
		String responseContent = "";
		Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		
		post.setRequestHeader(
				"User-Agent",
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:30.0) Gecko/20100101 Firefox/30.0");
		post.setRequestHeader("Host", "file.api.weixin.qq.com");
		post.setRequestHeader("Connection", "Keep-Alive");
		post.setRequestHeader("Cache-Control", "no-cache");
		post.setRequestHeader("Content-Type", "application/json");
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		try {
			post.setRequestBody(responeJsonStr);
			int status = client.executeMethod(post);
			if (status == HttpStatus.SC_OK) {
				responseContent = post.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return responseContent;
	}
}
